package gateway;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MobileAgentNaming {

	private Object lock = new Object();
	private List<String> addresses = new ArrayList<String>();
	private List<List<String>> mapsAgents = new ArrayList<List<String>>();

	private Map<String, List<String>> mapsAgent = new HashMap<String, List<String>>();

	public String getAddress(String agentID) {
		String result = "";

		synchronized (lock) {
			for (int i = 0; i < mapsAgents.size(); i++) {
				if (mapsAgents.get(i).indexOf(agentID) > -1) {
					result = addresses.get(i);
					break;
				}
			}
			lock.notifyAll();
		}

		return result;
	}

	public List<String> getNeighborsAddress() {
		List<String> list = null;
		
		synchronized(lock) {
			list = new ArrayList<String>(addresses);
			lock.notifyAll();
		}
		
		return list;
	}

	public List<String> getNeighborsAgents() {
		List<String> neighborsAgents = new ArrayList<String>();

		synchronized (lock) {
			for (List<String> l : mapsAgents) {
				for (String s : l) {
					neighborsAgents.add(new String(s));
				}
			}
			
			lock.notifyAll();
		}

		return neighborsAgents;
	}

	public List<String> getSpotAgents(String spotAddress) {
		List<String> agents = null;

		synchronized (lock) {
			int spotIndex = addresses.indexOf(spotAddress);
			agents = new ArrayList<String>(mapsAgents.get(spotIndex));
			
			lock.notifyAll();
		}

		return agents;
	}

	public void addSpotAgents(String spotAddress, List<String> newAgents) {

		synchronized (lock) {
			int spotIndex = addresses.indexOf(spotAddress);

			if (spotIndex == -1) {
				addresses.add(spotAddress);
				mapsAgents.add(newAgents);
			} else {
				addresses.set(spotIndex, spotAddress);
				mapsAgents.set(spotIndex, newAgents);
			}

			lock.notifyAll();
		}

	}
}
